
use image::GrayImage;
use libc::c_int;
use zint_ffi::ZBarcode_Create;
use zint_ffi::ZBarcode_Delete;
use zint_ffi::ZBarcode_Encode_and_Buffer;

mod zint_ffi;

fn main() -> Result<(), Box<dyn std::error::Error>> {

        let text = "123456789012";
        let my_symbol = unsafe {
            let my_symbol = ZBarcode_Create();
            // 1 代表 CODE_128
            (*my_symbol).symbology = 1;
            (*my_symbol).scale = 5.0;
            let c_data = std::ffi::CString::new(text).unwrap();
            let error_num = ZBarcode_Encode_and_Buffer(my_symbol, c_data.as_ptr() as * const u8, text.len() as c_int, 0);
        println!("error_num{}", error_num);
            my_symbol
        };

        let (gray_data, width, height) = unsafe {
            let width = (*my_symbol).bitmap_width as u32;
            let height = (*my_symbol).bitmap_height as u32;
            let bitmap = (*my_symbol).bitmap;
            let total_pixels = (width * height) as usize;

            let mut gray_data:Vec<u8> = Vec::with_capacity(total_pixels);
            
            // Zint 位图是 RGB 三通道排列
            for i in (0..(total_pixels * 3)).step_by(3) {
                let r = *bitmap.add(i);
                // 简单的亮度转换公式：Y = 0.299R + 0.587G + 0.114B
                // 这里简化为直接取 R 通道值（根据实际需求调整）
                let value = if r != 0 { 0xFF } else { 0x00 };
                gray_data.push(value);
            }
            
            (gray_data, width, height)
        };

        println!("length{}", gray_data.len());
        
        // 将数据转换为图像
        let img = GrayImage::from_raw(width, height, gray_data).unwrap();
        
        // 保存图像
        img.save("barcode.png")?;

        unsafe {
            ZBarcode_Delete(my_symbol);
        }
        
    
    Ok(())
}